package com.trsj.lnsj.service.imp;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trsj.lnsj.common.DataResponse;
import com.trsj.lnsj.common.MsgStatus;
import com.trsj.lnsj.entity.ActivityDTO;
import com.trsj.lnsj.entity.CollectionDTO;
import com.trsj.lnsj.entity.CollectionRepo;
import com.trsj.lnsj.mapper.ActivityMapper;
import com.trsj.lnsj.service.ICollectionService;
import com.trsj.lnsj.util.ResponseHelper;

@Service
public class CollectionService implements ICollectionService {
    private Logger logger = LoggerFactory.getLogger(CollectionService.class);
    @Autowired
    private CollectionRepo collectionRepo;
    @Autowired
    private ActivityMapper actMapper;

    @Override
    public DataResponse queryMyCollection(int pageNum, int pageSize, long userId, String type) {
        DataResponse resp = null;
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<ActivityDTO> actList = actMapper.selectCollectionActivityInfo(userId,type);
            PageInfo<ActivityDTO> page = new PageInfo<ActivityDTO>(actList);
            pageNum = pageNum - 1;
            int total = 0;
            PageRequest pageRequest = new PageRequest(pageNum, pageSize);
            Page<ActivityDTO> page1 = new PageImpl<ActivityDTO>(page.getList(), pageRequest, total);
            resp = ResponseHelper.getSuccessResponse(page1);
        } catch (Exception e) {
            logger.warn("error={}", e.getMessage());
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return resp;
    }

    @Override
    public DataResponse addCollection(long userId, long actId) {
        DataResponse resp = null;
        CollectionDTO collection = new CollectionDTO();
        collection.setActId(actId);
        collection.setUserId(userId);
        try {
            List<CollectionDTO> collectList = collectionRepo.findByUserIdAndActId(userId, actId);
            if (CollectionUtils.isNotEmpty(collectList)) {
                resp = ResponseHelper.getResponse(MsgStatus.DATA_REPEATED);
            } else {
                collectionRepo.saveAndFlush(collection);
                resp = ResponseHelper.getResponse(MsgStatus.STATUS_OK);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return resp;
    }
    
    public static void main(String[] args) {
        System.out.println(new Date().getTime() + "=" + System.currentTimeMillis());
    }
}
